package main;
/*
 * CloudStego school project
 * @author lauris kruusamae
 * @author triin uudam
 * @author uku loskit
 */
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

/**
 * Mapper implementation for message encoding
 * key - base image path
 * value - message image path
 * 
 * Reads the message image bytes and outputs each byte
 * with :
 * key - base image path
 * value - <byte index, byte value>
 * 
 * Byte indices are used for sorting of the bytes when recreating the image.
 *
 */
class EncodeMap extends Mapper<Text, Text, Text, Text> {
	
    protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileSystem fs = FileSystem.get(context.getConfiguration());
        FSDataInputStream in = null;
        try {
            in = fs.open(new Path(value.toString()));
            int nRead;
            byte[] buffer = new byte[1024];
            while ((nRead = in.read(buffer, 0, buffer.length)) != -1) {
				out.write(buffer, 0, nRead);
			}
        } finally {
            if (in != null) {
                in.close();
            }
            out.flush();
            out.close();
        }
        byte[] bytes = out.toByteArray();
        int byteCount = bytes.length;
        for (int index = 0; index < byteCount; index++) {
        	Text outValue = new Text(index + "," + bytes[index]);
        	context.write(key, outValue);
        }
    }
}
